from django.shortcuts import render
from django.views import View
from utils.goods import get_categories
import os.path
import time

from django.shortcuts import render
from django.views import View
from utils.goods import get_categories
from django.http import JsonResponse, HttpResponse, request
from apps.contents.models import ContentCategory
from apps.goods.models import GoodsCategory, SKU,GoodsVisitCount
from utils.goods import get_breadcrumb
from django.core.paginator import Paginator
# from haystack.views import SearchView
from datetime import date
from meiduo_mall.settings import BASE_DIR

# Create your views here.


class IndexView(View):
    def get(self, request):
        categories= get_categories()
        # 广告数据
        contents = {}
        content_categories = ContentCategory.objects.all()
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

            # 渲染模板的上下文
            context = {
                'categories': categories,
                'contents': contents,
            }

        return render(request, 'index.html', context)


class ListView(View):
    def get(self, request, category_id):
        # 1. 接收参数
        # 排序字段
        ordering = request.GET.get('ordering')
        # 每页多少条数据
        page_size = request.GET.get('page_size')
        # 要第几页数据
        page = request.GET.get('page')

        # 2. 获取分类id
        # 3. 根据分类id进行扽类数据的查询验证
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})
        # 4. 获取面包屑数据
        breadcrumb = get_breadcrumb(category)
        # 5. 查询分类对应的sku数据，然后排序。然后分页
        skus = SKU.objects.filter(category=category, is_launched=True).order_by(ordering)
        #      object_list  列表数据
        #      per_page     每页多少条数据
        paginator = Paginator(skus, page_size)
        # 获取指定页码的数据
        page_sku_list = paginator.page(page)

        sku_list = list()
        # 将对象转换为字典数据
        for sku in page_sku_list:
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url
            })
        # 获取总页码
        total_page = paginator.num_pages
        # 6. 返回响应
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'list': sku_list,
            'count': total_page,
            'breadcrumb': breadcrumb,
        })


class HostGoodsView(View):
    def get(self, request, category_id):
        # 获取销售量前二的商品
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:2]

        hot_list = list()

        for sku in skus:
            hot_list.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url
            })

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'hot_skus': hot_list
        })


"""
    我们/数据       <--------Haystack-------->      Elasticsearch

    我们是借助于  haystack  来对接  elasticsearch
    所以  haystack  可以帮助我们查询数据
"""
'''
class SKUSearchView(SearchView):
    def create_response(self):
        # 获取搜索的结果
        context = self.get_context()
        sku_list = list()

        for sku in context['page'].object_list:
            sku_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image.url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count
            })

        return JsonResponse(sku_list, safe=False)

'''
class VisitCountView(View):
    def post(self, request, category_id):
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 0, 'errcode': 400, 'errmsg': '参数错误'})

        today = date.today()

        try:
            goods_visit_count = GoodsVisitCount.objects.get(category=category, date=today)
        except GoodsVisitCount.DoesNotExist:
            GoodsVisitCount.objects.create(category=category, date=today, count=1)
        else:
            goods_visit_count.count += 1
            goods_visit_count.save()

        return JsonResponse({'code': 200, 'errmsg': 'ok'})
